package com.achen.service.impl;

import com.achen.dao.MenuDao;
import com.achen.entity.Menu;
import com.achen.service.MenuService;
import com.achen.util.Constant;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;

/**
 * @author achen
 * @create 2020-04-30 19:08
 */
@Service
@Transactional
public class MenuServiceImpl implements MenuService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MenuDao menuDao;

    @Override
    public List<Menu> findAll() {
        //从redis缓存中取menu，查看是否存在
        String menuCache = stringRedisTemplate.opsForValue().get(Constant.MENU_CACHE);
        //创建一个集合
        List<Menu> list = null;
        //如果为空，加入到缓存
        if(menuCache == null){
            //从dao中取数据
            list = menuDao.findAll();
            try {
                //序列化
                String json = new ObjectMapper().writeValueAsString(list);
                //将集合存入redis缓存
                stringRedisTemplate.opsForValue().set(Constant.MENU_CACHE,json);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }else{
            //如果不为空，反序列化，赋值响应给前台
            System.out.println("从缓存中取得数据");
            try {
                list = new ObjectMapper().readValue(menuCache, List.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return list;
    }
}
